/**
 * 页面初始化公用函数
 */
import sqlService from '@/api/sqlService'
import widgetService from '@/api/widgetService'
import { SQLCONFIG_TYPE_LIST } from '@/constant'
import btnEvent from '@/api/btnEvent'

export default function (ctx) {
  this.loadData = async (params) => {
    const sqlParam = {
      sqlConfigName: ctx.sqlConfigDTO.name,
      pageIndex: ctx.filter.pageIndex,
      pageSize: ctx.filter.pageSize,
      params: params
    }
    ctx.table.loading = true
    await sqlService.pageQuery(sqlParam).then((d) => {
      ctx.table.dataSource = d.rows
      ctx.table.pagination.total = d.total
      if (ctx.table.rowSelection) {
        ctx.table.rowSelection.selectedRowKeys = []
      }
      ctx.table.loading = false
    })
  }
  /**
   * 设置行样式
   * @param record 行数据
   * @param fieldName 比较字段，默认为id，为customRow中记录的rowId
   * @returns {string}
   */
  this.setRowClassName = (record, fieldName = 'id') => {
    var className = ''
    if (record.taskStatus) {
      if (record[fieldName] === ctx.rowId) {
        className = 'font-normal selected'
      } else {
        className = 'font-normal'
      }
    } else {
      if (record[fieldName] === ctx.rowId) {
        className = 'font-bold selected'
      } else {
        className = 'font-bold'
      }
    }
    return className
  }
  this.handleBtnClick = (btn) => {
    ctx.owner[btn.operate](btn)
  }
  /**
   * 设置行点击和双击处理函数
   * @param record 行数据
   * @param fieldName 记录字段，默认为id
   * @returns {{on: {dblclick: on.dblclick, click: on.click}}}
   */
  this.customRow = (record, fieldName = 'id') => {
    return {
      on: {
        click: () => {
          ctx.rowId = record[fieldName]
          ctx.rowData = record
          // 单击项目名称进入任务详情页面
          if (record.key && ['projectName', 'xmmc', 'PROJECTNAME', 'CASECODE', 'XMMC'].includes(record.key.dataIndex)) {
            const dblBtn = ctx.$refs.btnWidget.dblBtn
            if (dblBtn) {
              const params = {}
              if (dblBtn.desc) {
                try {
                  const $desc = JSON.parse(dblBtn.desc)
                  if ($desc.readonly) {
                    params.readonly = true
                  }
                } catch (e) {

                }
              }
              ctx.owner[dblBtn.operate](dblBtn, params)
            }
          }
        },
        dblclick: () => {
          const dblBtn = ctx.$refs.btnWidget.dblBtn
          const params = {}
          if (dblBtn.desc) {
            try {
              const $desc = JSON.parse(dblBtn.desc)
              if ($desc.readonly) {
                params.readonly = true
              }
            } catch (e) {

            }
          }
          if (dblBtn) {
            ctx.owner[dblBtn.operate](dblBtn, params)
          }
        }
      }
    }
  }
  this.listCusWidSqlConfigDTOsByCusId = async (type) => {
    await widgetService.getCustomWidgetSqlConfigDTO(ctx.customWidgetId, type || SQLCONFIG_TYPE_LIST).then(({ tableHeader, sqlConfigDTO }) => {
      ctx.sqlConfigDTO = sqlConfigDTO
      const columns = []
      JSON.parse(tableHeader).forEach(({ tableHeaderName, sqlConfigName, align, width, ellipsis }) => {
        // 之前的版本
        // columns.push({
        //   title: tableHeaderName,
        //   dataIndex: sqlConfigName,
        //   align: align || undefined,
        //   width: width || undefined,
        //   ellipsis: ellipsis || false,
        //   scopedSlots: {
        //     customRender: sqlConfigName
        //   }
        // })

        // 修改后
        // 【在办任务】列表增加自动排序功能，可按照 受理时间，承诺办结时间排序
        var columnObj = {}
        columnObj.title = tableHeaderName
        columnObj.dataIndex = sqlConfigName
        columnObj.align = align || undefined
        columnObj.width = width || undefined
        columnObj.ellipsis = ellipsis || false
        columnObj.scopedSlots = {
          customRender: sqlConfigName
        }
        // if (ctx.customWidgetId === '402886cb8479f1fd0184989c5fbf059a') {
          if (sqlConfigName === 'createTime') {
            columnObj.sorter = (a, b) => { return Date.parse(a.createTime) - Date.parse(b.createTime) }
          } else if (sqlConfigName === 'dueTime') {
            columnObj.sorter = (a, b) => { return Date.parse(a.dueTime) - Date.parse(b.dueTime) }
          } else if (sqlConfigName === 'applydate') {
            columnObj.sorter = (a, b) => { return Date.parse(a.applydate) - Date.parse(b.applydate) }
          } else if (sqlConfigName === 'GQTS') {
            columnObj.sorter = (a, b) => { return Date.parse(a.GQTS) - Date.parse(b.GQTS) }
          } else if (sqlConfigName === 'gqsj') {
            columnObj.sorter = (a, b) => { return Date.parse(a.gqsj) - Date.parse(b.gqsj) }
          } else if (sqlConfigName === 'STARTDATE') {
            columnObj.sorter = (a, b) => { return Date.parse(a.STARTDATE) - Date.parse(b.STARTDATE) }
          } else if (sqlConfigName === 'ENDDATE') {
            columnObj.sorter = (a, b) => { return Date.parse(a.ENDDATE) - Date.parse(b.ENDDATE) }
          } else if (sqlConfigName === 'CREATETIME') {
            columnObj.sorter = (a, b) => { return Date.parse(a.CREATETIME) - Date.parse(b.CREATETIME) }
          } else if (sqlConfigName === 'collectTime') {
            columnObj.sorter = (a, b) => { return Date.parse(a.collectTime) - Date.parse(b.collectTime) }
          }
        // }
        columns.push(columnObj)
      })

      ctx.table.columns = columns
    })
  }
  this.setWidgets = async (filterBtn) => {
    if (filterBtn && ctx.taskId) {
      ctx.widgets = await widgetService.filterCustomWidgetBtn(ctx.customWidgetId, ctx.projectId, ctx.taskId, ctx.projectInfo.businessId)
    } else {
      ctx.widgets = await widgetService.listCustomWidgetBtnByParentId(ctx.customWidgetId, window.config.VUE_APP_NAME.split(',')[0], ctx.userInfo.id)
    }
    // ctx.widgets = await widgetService.listCustomWidgetBtnByParentId(ctx.customWidgetId)
    if (ctx.widgets && ctx.widgets.length > 0) {
      const pageDetail = ctx.widgets[0]
      if (pageDetail.usedWidgetId) {
        widgetService.getCustomWidgetById(pageDetail.usedWidgetId).then((data) => {
          ctx.pageDetailRoute = data
        })
      }
    }
  }
  // 页面创建完成，初始化页面id、绑定业务组件id、页面按钮处理函数
  this.created = () => {
    /* if(ctx.$route.meta.matterType === '智慧选址') {
      dicService.treeDicItemByDicName('智慧选址项目类型').then(res => {
        ctx.xmlxDic = res
      })
    } */
    ctx.customWidgetId = ctx.$route.meta.id
    ctx.modelWidgetId = ctx.$route.meta.modelId
    ctx.owner = btnEvent.createProcessor(ctx)
  }
  // 挂载，获取页面绑定按钮，queryTable是否查询页面绑定sql
  this.mounted = async (queryTable = true, filterBtn = false) => {
    await this.setWidgets(filterBtn)
    if (queryTable) {
      await this.listCusWidSqlConfigDTOsByCusId(ctx.listType)
      await ctx.loadData()
    }
  }
  // 获取绑定的list子表名称集合
  this.getTableNames = (content) => {
    const arr = []
    if (typeof content === 'string') {
      content = JSON.parse(content)
    }
    // 递归遍历控件树
    const traverse = (array) => {
      array.forEach((element) => {
        ctx.keyAndModelMap[element.model] = element.label || element.desc
        if (element.type === 'grid' || element.type === 'tabs') {
          // 栅格布局 and 标签页
          element.columns.forEach((item) => {
            traverse(item.list)
          })
        } else if (['card', 'batch', 'block', 'collapse'].includes(element.type)) {
          // 卡片布局，动态表格，
          if (['batch', 'block'].includes(element.type)) {
            arr.push(element.model)
          }
          traverse(element.list)
        } else if (element.type === 'table') {
          // 表格布局
          element.trs.forEach((item) => {
            item.tds.forEach((val) => {
              traverse(val.list)
            })
          })
        }
      })
    }
    traverse(content.list)
    return arr
  }
}

// 弹出遮罩层
export function loading (msg, className, parent) {
  let el = document.querySelector('.my-loading')
  if (!el) {
    el = document.createElement('div')
    el.className = 'my-loading'
    const icon = document.createElement('div')
    icon.className = 'loading-icon'
    icon.innerHTML = '<div class="inner"></div><div class="inner"></div><div class="inner"></div><div class="inner"></div>'
    const text = document.createElement('div')
    text.className = 'loading-text' + (className ? ' ' + className : '')
    text.appendChild(icon)
    text.appendChild(document.createElement('p'))
    el.appendChild(text)
    const p = parent || document.body
    p.appendChild(el)
  }
  const text = el.querySelector('.loading-text p')
  text.innerText = msg || '正在操作，请稍候！'
  return closeMyLoading
}

// 关闭遮罩层
export function closeMyLoading () {
  const loadingDialog = document.querySelector('.my-loading')
  if (loadingDialog) {
    loadingDialog.remove()
  }
}
